<!--公告管理-->
<template>
    <div class="card" >
        <el-button type="primary" @click="handleAddNotification">新增公告</el-button>
        <el-input :prefix-icon="Search" placeholder="请输入要查询的公告内容"
                  v-model="searchNotification"
                  clearable
                  style="width: 290px; margin: 0 20px 0 50px"/>
        <el-button @click="reset">重置</el-button>
        <el-button type="primary" @click="loadNotifications">查询</el-button>
    </div>
    <div class="card">
        <!-- 公告列表 -->
        <div>
            <el-table :data="noticeList" stripe
                      :header-cell-style="{ fontWeight: 'bold', color: '#1d1c1c', textAlign: 'center', backgroundColor: '#f5f4f1'}"
                      :cell-style="{ textAlign: 'center', height: '70px' }"
                      fit
            >
                <el-table-column prop="messageId" label="公告ID" width="80"></el-table-column>
                <el-table-column prop="title" label="标题" width="160"></el-table-column>
                <el-table-column prop="content" label="内容" width="400" show-overflow-tooltip></el-table-column>
                <el-table-column prop="createdAt" label="发布时间" width="160"></el-table-column>
                <el-table-column label="操作">
                    <template #default="scope">
                        <el-button type="danger" size="small" @click="deleteNotice(scope.row.messageId)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination
                v-model:current-page="pageNum"
                v-model:page-size="pageSize"
                :total="total"
                :page-sizes="[5, 10, 20]"
                layout="total, sizes, prev, pager, next, jumper"
                @current-change="loadNotices"
                @size-change="loadNotices"
            ></el-pagination>
        </div>
    </div>
    <el-dialog v-model="isNotification">
        <el-form :model="data.noticeForm" :rules="rules" ref="formRef">
            <el-form-item label="公告标题" prop="title">
                <el-input v-model="data.noticeForm.title" placeholder="请输入公告标题"></el-input>
            </el-form-item>
            <el-form-item label="公告内容" prop="content">
                <el-input type="textarea" v-model="data.noticeForm.content" rows="4" placeholder="请输入公告内容"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="sendMessage">发布公告</el-button>
                <el-button @click="resetForm">取消</el-button>
            </el-form-item>
        </el-form>
    </el-dialog>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted, getCurrentInstance } from 'vue';
import { markRaw } from 'vue'
import {Delete, Search} from "@element-plus/icons-vue";
import request from "@/utils/request.js";
import {ElMessage, ElMessageBox} from "element-plus";

const pageNum = ref(1)
const pageSize = ref(10)
const total = ref(0)

//获取本地存储中的用户信息
let user;
const loginUser = localStorage.getItem('code_user');
if (loginUser) {
    // 将拿到的Json数据转化为JavaScript对象
    user = JSON.parse(loginUser);
}

const searchNotification = ref('')

const data = reactive({
    noticeForm: {},
})
const isNotification = ref(false)
const handleAddNotification = () => {
    isNotification.value = !isNotification.value
    data.noticeForm = {}
}
const rules = {
    title: [
        { required: true, message: '请输入公告标题', trigger: 'blur' }
    ],
    content: [
        { required: true, message: '请输入公告内容', trigger: 'blur' }
    ]
};

const formRef = ref();  // 表单绑定
const noticeList = ref([]);  // 公告列表

// 加载公告列表
const loadNotices = () => {
    request.get('/api/notice/list', {
        params: {
            pageNum : pageNum.value,
            pageSize : pageSize.value,  //添加参数给后端实现分页
            content: searchNotification.value,  // 模糊查询条件
        }
    }).then(res => {
        if (res.code === '200') {
            noticeList.value = res.data.list;
            total.value = res.data.total;
        } else {
            console.log(res.msg)
        }
    });
};

// 发送公告
const sendMessage = () => {
    if (!data.noticeForm.title || !data.noticeForm.content) {
        ElMessage.warning('请填写公告标题和内容');
        return;
    }
    const message = {
        title: data.noticeForm.title,
        content: data.noticeForm.content,
        messageType: 'SYSTEM'
    };
    console.log(message)
   // 消息发送方法
    request.post('/api/notice/addNotice', message).then(res => {
        if (res.code === '200') {
            ElMessage.success("发布公告成功")
            loadNotices() // 更新公告列表
            isNotification.value = false // 关闭弹窗
        } else {
            ElMessage.error("公告发布失败" + res.msg)
        }
    })
};

// 打开关闭重置表单
const resetForm = () => {
    data.noticeForm.title = '';
    data.noticeForm.content = '';
    isNotification.value = !isNotification.value
};

// 删除公告
const deleteNotice = (messageId) => {
    ElMessageBox.confirm('确定删除此公告嘛！', '删除确认', {type: 'warning', icon: markRaw(Delete),}).then(res => {
        request.delete('/api/notice/delete/' + messageId).then(res => {
            if (res.code === '200') {
                ElMessage.success("删除成功")
                loadNotices()
            } else {
                ElMessage.error("删除失败：" + res.msg)
            }
        })
    }).catch(err => {
        console.error('删除公告出错:', err);
        ElMessage.error('网络错误，请稍后重试');
    })
};
// 搜索公告
const loadNotifications = () => {
    pageNum.value = 1; // 重置为第一页
    loadNotices();
};
// 重置搜索
const reset = () => {
    searchNotification.value = ''
    loadNotices();
}

onMounted(() => {  // 初始化加载
    loadNotices()
});

onUnmounted(() => {  // 结束会话，断开连接

});
</script>